// shopPages/Customerxq/Customerxq.js
import {

  baseUrl
} from "../../utils/api.js";
import * as echarts from '../ec-canvas/echarts';
import time_change from "../../utils/util.js";
var page = 1;
var newsList = [];
var selectedNews = false;
var mid = ''
const app = getApp();

function initChart(canvas, width, height) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);

  var url = '/log_api/analysisList';
  var params = {
    operation_id: app.globalData.userInfo.id,
    user_id: mid,
  };
  app.HttpGetSend(url, params, function(res) {

    if (res.msg != "success") {
      console.log(res.data)


    } else {
      console.log(res.data)

      var option = {
        backgroundColor: "#ffffff",
        color: ["#37A2DA", "#32C5E9", "#67E0E3", "#91F2DE", "#FFDB5C", "#FF9F7F"],
        series: [{
          label: {
            normal: {
              fontSize: 12,
              rich: {}
            }
          },

          type: 'pie',
          center: ['50%', '50%'],
          radius: [0, '60%'],
          data: [{
            value: res.data.loveCompanyPercent,
            name: '对公司感兴趣'
          }, {
            value: res.data.loveGoodsPercent,
            name: '对商品感兴趣'
          }, {
            value: res.data.loveMePercent,
            name: '对我感兴趣'
          }, ],
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 2, 2, 0.3)'
            }
          }
        }]
      };

      chart.setOption(option);
      return chart;



    }
  });

}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customerIndex: 0,
    itemList: ['潜在客户', '意向客户', '客户'],
    userType: 0,
    inputTag: '',
    tagstring: '',
    tagsList: [],
    isShowtag: false,
    current: 0,
    customer: '',
    customerList: [],
    list: [],
    contentList: [],
    genjinList: [],
    timeList: [],
    genjinTimeList: [],
    orderList: [],
    phone: '',
    totalCount: '',
    isSelect: [{
        name: '行为',
        isSelect: true
      },
      {
        name: '跟进记录',
        isSelect: false
      },
      {
        name: '标签',
        isSelect: false
      },
      {
        name: 'AI分析',
        isSelect: false
      },
      {
        name: '订单',
        isSelect: false
      },
    ],
    ec: {
      onInit: initChart
    },
    boosid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    page = 1
    selectedNews = false;
    newsList = []
    mid = options.mid
    this.setData({
        customerIndex: options.index,
        totalCount: options.totalCount
      }),
      console.log(mid)
    // 获取boosid
    var url2 = "/user_api/get_boss_id"
    var params2 = {
      uid: app.globalData.userInfo.id
    };
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg !== "成功") {
        app.showTipMsg(res.msg);
      } else {
        console.log(res)
        that.setData({
          boosid: res.data
        })
      }
    });

    //获取用户详情

    wx.request({
        url: app.globalData.bossradar + '/api/1.0/getUserInfo',
        data: {
          // mid
          operationId: app.globalData.userInfo.id, //客户id
          uid: mid,
        },
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data)
          that.setData({
            customer: res.data.data,
            userType: res.data.data.userType,
          })

          if (res.data.data.phone.length != 0) {
            that.setData({
              phone: res.data.data.phone
            })
          } else {
            that.setData({
              phone: '暂未填写'
            })
          }
          // that.data.customer = ;
        }
      }),
      //获取行为
      that.getLog();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (selectedNews == true) {
      var that = this;
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      // 页数+1  
      if (that.data.current == 0) {
        that.getLog();
      } else if (that.data.current == 4) {
        that.getOrderList()
      }
    } else {
      wx.hideLoading();
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // },
  // 切换tab
  changeSelect(e) {
    var that = this
    page = 1;
    newsList = []
    this.setData({
      current: e.currentTarget.id
    })
    if (e.currentTarget.id == 0) {
      that.getLog();
    } else if (e.currentTarget.id == 1) {
      //获取跟进记录
      that.getgenjin();
    } else if (e.currentTarget.id == 2) {
      //获取标签
      that.getTags();
    } else if (e.currentTarget.id == 3) {

    } else if (e.currentTarget.id == 4) {
      //获取订单
      that.getOrderList();

    }
  },

  changeSwiper(e) {
    this.setData({
      current: e.detail.current
    })
  },
  addGenjin: function() {
    console.log(this.data.totalCount);
    wx.navigateTo({
      url: '/shopPages/addgenjin/addgenjin?uid=' + mid + '&logo=' + this.data.customer.logo + '&name=' + this.data.customer.name + '&index=' + this.data.customerIndex + '&totalCount=' + this.data.totalCount + '&userType=' + this.data.userType,
    })
  },
  genjinRemind: function() {
    wx.navigateTo({
      url: '/shopPages/genjin/genjin?mid=' + mid,
    })
  },
  //获取行为
  getLog: function() {
    var that = this;
    wx.request({
      url: app.globalData.bossradar + '/api/1.0/getLogListByCustomer',
      data: {
        uid: mid, //客户id
        page: page,
        pageSize: 15,
        operationId: app.globalData.userInfo.id,
        isBoss: app.globalData.userInfo.is_boss == 1 ? true : false
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)

        var contentList = [];
        var timelist = [];
        for (var i = 0; i < res.data.data.list.length; i++) {
          var time = time_change.imestampToTime(res.data.data.list[i].updateTime)
          res.data.data.list[i].show_time = time;
          switch (res.data.data.list[i].logType) {
            case 1:
              res.data.data.list[i].log_desc = '点赞了' + res.data.data.list[i].operationName + '人脉';
              break;
            case 2:
              res.data.data.list[i].log_desc = '收藏了' + res.data.data.list[i].operationName + '人脉';
              break;
            case 30:
              res.data.data.list[i].log_desc = '保存了' + res.data.data.list[i].operationName + '人脉海报';
              break;
            case 3:
              res.data.data.list[i].log_desc = '分享了' + res.data.data.list[i].operationName + '人脉';
              break;
            case 5:
              res.data.data.list[i].log_desc = '浏览了' + res.data.data.list[i].operationName + '人脉';
              break;
            case 13:
              if (res.data.data.list[i].goodName == '') {
                res.data.data.list[i].log_desc = '浏览了' + res.data.data.list[i].operationName + '商城';
              } else {
                res.data.data.list[i].log_desc = '浏览了' + res.data.data.list[i].operationName + '' + res.data.data.list[i].goodName;
              }
              break;
            case 31:
              res.data.data.list[i].log_desc = '把商品' + res.data.data.list[i].goodName + '加入购物车';
              break;
            case 18:
              res.data.data.list[i].log_desc = '下单了' + res.data.data.list[i].operationName + '' + res.data.data.list[i].goodName + '商品';
              break;
            case 32:
              res.data.data.list[i].log_desc = '分享了' + res.data.data.list[i].operationName + '' + res.data.data.list[i].goodName + '商品';
              break;
            case 33:
              res.data.data.list[i].log_desc = '保存了' + res.data.data.list[i].operationName + '' + res.data.data.list[i].goodName + '商品图片';
              break;
            case 6:
              res.data.data.list[i].log_desc = '打开了聊天页面';
              break;
            case 7:
              res.data.data.list[i].log_desc = '访问了' + res.data.data.list[i].operationName + '官网';
              break;
            case 9:
              res.data.data.list[i].log_desc = '播放了' + res.data.data.list[i].operationName + '视频介绍';
              break;
            case 10:
              res.data.data.list[i].log_desc = '播放了' + res.data.data.list[i].operationName + '语音介绍';
              break;
            case 14:
              res.data.data.list[i].log_desc = '点击了购买名片';
              break;
            case 34:
              res.data.data.list[i].log_desc = '购买了名片';
              break;
            case 35:
              res.data.data.list[i].log_desc = '购买名片成功';
              break;

            case 17:
              res.data.data.list[i].log_desc = '添加了收货地址';
              break;
            case 18:
              res.data.data.list[i].log_desc = '提交订单';
              break;
            case 19:
              res.data.data.list[i].log_desc = '商品付款成功';
              break;
            case 20:
              res.data.data.list[i].log_desc = '取消订单';
              break;
            case 21:
              res.data.data.list[i].log_desc = '动态点赞';
              break;
            default:
              break;
          }
          newsList.push(res.data.data.list[i]);
        }

        if (res.data.data.list.length < 15) {
          selectedNews = false;
        } else {
          selectedNews = true;
          page += 1;
        }
        that.setData({
          list: newsList,
        });
        wx.hideLoading();
      }
    })
  },
  //跟进记录
  getgenjin: function() {
    var that = this;
    wx.request({
      url: app.globalData.bossradar + '/api/1.0/getFollowList',
      data: {
        bossId: app.globalData.userInfo.id,
        uid: mid, //客户id
        page: 1,
        pageSize: 20
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        var timelist = [];
        for (var i = 0; i < res.data.data.list.length; i++) {
          var time = time_change.imestampToTime(res.data.data.list[i].updateTime)
          console.log(time)
          timelist.push(time);
        }

        that.setData({
          genjinList: res.data.data.list,
          genjinTimeList: timelist,
          totalCount: res.data.data.totalCount
        })

      }
    })
  },
  //获取标签
  getTags: function() {
    var that = this;
    wx.request({
      url: app.globalData.bossradar + '/api/1.0/getUserLabel',
      data: {
        uid: mid, //客户id
        operationId: app.globalData.userInfo.id, //用户ID
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log("---------------")
        if (res.data.data == '[object Object]') {
          console.log("---------=========================================------" + res.data.data)
          that.setData({
            tagstring: ''
          });
        } else {
          that.setData({
            tagstring: res.data.data
          });
        }

        // that.setData({
        //   tagstring: res.data.data
        // });
        console.log(res.data)
        var list = [];
        if (res.data.data.length == 0) {

        } else {
          list = res.data.data.split(',');
        }

        console.log(list)
        that.setData({
          tagsList: list
        })
        console.log(that.data.tagsList)
      }
    })
  },
  //更新标签
  updataTags: function() {

    this.setData({
      isShowtag: true
    });

  },

  //添加标签
  addtags: function() {

    console.log("---------------")
    this.setData({
      isShowtag: false
    });
    var that = this;
    var tag = '';

    if (that.data.inputTag.length == 0 & that.data.tagstring.length == 0) {


      wx.request({
        url: app.globalData.bossradar + '/api/1.0/modifyCustomerLabel',
        data: {
          belongUid: app.globalData.userInfo.id, //客户id
          uid: mid, //用户ID
          label: ''
        },
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data)
          that.setData({
            inputTag: ''
          })
          that.getTags();
        }
      })

    } else {
      if (that.data.inputTag.length == 0) {
        tag = that.data.tagstring;
      } else {
        if (that.data.tagstring.length == 0) {
          tag = that.data.inputTag;
        } else {
          tag = that.data.tagstring + ',' + that.data.inputTag;
        }
      }
      console.log(tag)
      wx.request({
        url: app.globalData.bossradar + '/api/1.0/modifyCustomerLabel',
        data: {
          belongUid: app.globalData.userInfo.id, //客户id
          uid: mid, //用户ID
          label: tag
        },
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data)
          that.setData({
            inputTag: ''
          })
          that.getTags();
        }
      })
    }
  },
  inputTag: function(e) {
    console.log(e.detail.value);
    this.setData({
      inputTag: e.detail.value
    })
  },

  deltags: function(e) {
    console.log(e);
    this.data.tagsList.splice(e.currentTarget.id, 1);
    console.log(this.data.tagsList);
    if (this.data.tagsList.length == 0) {
      this.data.tagstring = '';
    } else {
      this.data.tagstring = this.data.tagsList[0];
    }

    this.data.inputTag = '';
    for (var i = 1; i < this.data.tagsList.length; i++) {
      this.data.tagstring = this.data.tagstring + ',' + this.data.tagsList[i]
    }
    this.setData({
      tagsList: ''
    });
    console.log(this.data.tagstring)

    this.addtags();

  },
  // 订单
  getOrderList: function() {
    var that = this;
    wx.request({
      url: baseUrl + '/order/order_index',
      data: {
        uid: mid, //客户id
        mid: that.data.boosid, //用户ID
        page: page,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        var oredr_list = res.data.data
        console.log(oredr_list);
        for (var i = 0; i < oredr_list.length; i++) {
          newsList.push(oredr_list[i])
        }
        if (oredr_list.length < 10) {
          selectedNews = false;
        } else {
          selectedNews = true;
          page += 1;
        }
        that.setData({
          orderList: newsList
        })
        wx.hideLoading();
      }
    })
  },
  selectType: function() {
    var that = this;
    console.log(that.data.customer.userType)
    if (that.data.customer.userType == 2) {

    } else {
      wx.showActionSheet({
        itemList: ['潜在客户', '意向客户'],
        success(res) {
          console.log(res.tapIndex)
          that.setData({
            userType: res.tapIndex
          })
          wx.request({
            url: app.globalData.bossradar + '/api/1.0/modifyCustomerUserType',
            data: {
              belongUid: app.globalData.userInfo.id, //客户id
              uid: mid, //用户ID
              userType: res.tapIndex
            },
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              console.log(res.data)

              console.log(that.data.userType);
              wx.showToast({
                title: '修改成功',
              })
            }
          })
        },
      })
    }


  },

  doPhone: function(e) {
    console.log(e);
    if (e.currentTarget.id == 0) {
      wx.makePhoneCall({
        phoneNumber: this.data.customer.phone //仅为示例，并非真实的电话号码
      })
    } else {
      wx.navigateTo({
        url: '../../pages/socks/socks?mid=' + mid
      })
      app.addlog(app.globalData.userInfo.id, app.globalData.userInfo.username, mid, this.data.customer.username, '', 6, '')
    }
  }
})